//挂载vue实例，获取全局变量

import Vue from 'vue'
const vm = new Vue()
import {api_url} from './config';

//单文件选择，一步到位（不推荐的方法）
export async function simpleUploadImg(url,data) {
	let [ err,res ] = await uni.chooseImage()
	console.log('chooseImage',err, res)
	if(res && res.errMsg === 'chooseImage:ok'){
		let max = 10485760 //10M
		let size = res.tempFiles[0].size
		if(size < max){ // 不能大于10M
			return await upLoadImg(url,res.tempFilePaths[0],data)
		}else {
			throw new Error('ChooseImage Size Fail')
		}
	}
	else{
		throw new Error('ChooseImage Fail')
	}
}

//调用上传文件接口（使用起来比较灵活）
export function upLoadImg(url,file,data) {
	
	return new Promise((resolve,reject) => {
		uni.showLoading({
			title: '上传中...'
		})
		console.log('上传文件',api_url + url,file)
		uni.uploadFile({
			url: api_url + url,
			filePath: file,
			name: 'file',
			header: {
				"Authorization": 'Bearer ' + uni.getStorageSync('access_token')
			},
			formData: data,
			success: res => {
				res.filePath = file
				console.log('uploadFile success', res)
				resolve(res)
			},
			fail: (err) => {
				console.log('uploadFile fail', err)
				reject()
			},
			complete: () => {
				uni.hideLoading()
			}
		})
	})
}